所有向服务器提交的HTTP数据,其实都是一个表单

FromData是一种容器,用于模拟表单,向服务器提交数据,有两种使用方法

  • 创建空白FromData对象,然后向其中添加数据
  • 将<from>标签直接转化为一个FromData对象

使用FromData

注册一个用户:

async register(uName,uPwd){
    let fromData = new FormData();
    fromData.append('name',uName);
    fromData.append('pwd',uPwd);
    try {
      let res = await fetch('/api/adduser',{
        method:'POST',
        body:fromData
      })
  
      const {ok,err} = await res.json();
      if(ok){
        console.log('add user ok!')
      }else{
        console.log('add user fail!');
      }
    } catch (error) {
      console.log('error:',error)
    }
  }
  

上面的代码就简单介绍了FromData的第一种用法(创建对象的方式),接下来针对fetch进行下简单的封装

封装fetch

fetch.js

const BASEURL="http://localhost:3000/api"

export default async function(url,options){
    try {
        const res = await fetch(url,options);
        const {ok,error,data} = await res.json();
        if(ok){
            return data
        }else{
            console.error(error);
            throw new Error(error)
        }
    } catch (error) {
        throw error
    }
}

FromData+React+React-Redux结合使用

注册用户,并显示用户列表:

Reg.js

import React, { Component } from 'react';
import {connect} from 'react-redux'
import fetchJson from '../fetch'
import { from } from '_rxjs@6.5.2@rxjs';
class Reg extends Component {

    async submit(){
        // let fromData = new FormData();
        // fromData.append('name',this.refs.name.value);
        // fromData.append('pwd',this.refs.password.value);
        let fromData = new FormData(this.refs.from1);
        let data = await fetchJson('/api/adduser',{
            method:'POST',
            body:fromData
        })
        this.props.add_user({
            name:this.refs.name.value,
            pwd:this.refs.password.value
        })
        this.refs.name.value = "";
        this.refs.password.value = "";
    }

    render() {
        return (
            <div>
                <from ref="from1">
                    用户:<input type="text" name="name" ref="name"/><br/>
                    密码:<input type="password" name="password" ref="password"/><br/>
                    <input type="button" value="注册" onClick={this.submit.bind(this)}/>
                </from>
            </div>
        );
    }   
}

export default connect((state,props) => Object.assign({},props,state),{
    add_user(user){
        return{
            type:'ADD_USERS',
            user
        }
    }
})(Reg);

Table.js

import React, { Component } from 'react';
import {connect} from 'react-redux'
import fetchJson from '../fetch'

class Table extends Component {
    constructor(){
        super();
    }
    async componentDidMount(){
        const data = await fetchJson('/api/userlist');
        this.props.init_users(data)
    }
    render() {
        return (
            <div>
                <table border="1" width="100%">
                  <thead>
                    <tr>
                        <th>用户名</th>
                        <th>密码</th>
                    </tr>
                  </thead>
                  <tbody>
                     {
                         this.props.users.map(({...item},index)=>(
                            <tr key={index}>
                                <td>{name}</td>
                                <td>{pwd}</td>
                            </tr>
                         ))
                     }
                  </tbody>  
                </table>
            </div>
        );
    }
}

export default connect((state,props) => Object.assign({},props,state),{
    init_users(users){
        return{
            type:'SET_USERS',
            users
        }
    }
})(Table);

App.js

import React, { Component } from 'react';
import Table from './components/Table'
import Reg from './components/Reg'
class App extends Component {
  render() {
    return (
      <div>
        <Reg/>
        <Table/>
      </div>
    );
  }
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { async } from 'q';
import {Provider} from 'react-redux'
import store from './store'
ReactDOM.render(
    <Provider store={store}>
       <App />     
    </Provider>, 
    document.getElementById('root')
    );

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

store.js

import {createStore,combineReducers} from 'redux'

function users(state=[],action){
    switch(action.type){
        case 'SET_USERS':
            return action.users
        case 'ADD_USERS':
            return [
                ...state,
                action.user
            ]

        default:
            return state
    }
}

export default createStore(combineReducers({
    users
}))

总结:

  • 使用FromData创建对象,并append的方式适合小量数据,并不易变的操作
  • 使用from表单直接转换成FromData的方式更加灵活,可控

前端扫地僧
2.5k 声望1.2k 粉丝

慢慢理解世界、慢慢更新自己